package Servlet.member;

import Utils.StringUtils;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;


@WebServlet("/code")
public class CodeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        // 生成验证码
        String code = StringUtils.getCode(3);
        // 获取session
        HttpSession session = request.getSession();
        // 将验证码存入session中
        session.setAttribute("code",code);


        int WIDTH = 70;
        int HEIGHT = 35;

        // 创建一张图片
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        // 拿笔
        Graphics2D g = (Graphics2D) image.getGraphics();
        // 设置笔的颜色
        g.setColor(StringUtils.getColor());
        // 填充图片背景
        g.fillRect(0, 0, WIDTH, HEIGHT);
        // 设置笔颜色
        g.setColor(StringUtils.getColor());

        //生成干扰线
        for (int i = 0; i < 15; i++) {
            Random random = new Random();
            int x = random.nextInt(WIDTH);
            int y = random.nextInt(HEIGHT);
            int xl = random.nextInt(WIDTH);
            int y1 = random.nextInt(HEIGHT);
            g.drawLine(x, y, xl, y1);
        }

        //生成噪点
        for (int i = 0; i < 500; i++) {
            Random ran = new Random();
            int x = ran.nextInt(WIDTH);
            int y = ran.nextInt(WIDTH);
            g.drawOval(x, y, 1, 1);
        }

        // 设置字体、大小
        g.setFont(new Font("Arial", Font.BOLD, 30));
        // 画
        g.drawString(code, 1, 30);

        // 并以图片的方式发送给浏览器，不让浏览器缓存
        response.setContentType("image/jpeg");
        response.setDateHeader("expires", 0);
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");

        // 发送给浏览器
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);

        out.close();

        System.out.println("codeservlet:"+code);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
